package com.sjf.filter;

import com.alibaba.fastjson.JSON;
import com.sjf.common.BaseContext;
import com.sjf.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 自定义过滤器
 * @author <huangtang>
 * @since 2022/4/25 12:39
 **/
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {


    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher ();
    @Override
    public void doFilter ( ServletRequest servletRequest , ServletResponse servletResponse , FilterChain filterChain ) throws IOException, ServletException {
        HttpServletRequest request = ((HttpServletRequest)servletRequest);
        HttpServletResponse response = ((HttpServletResponse)servletResponse);
        //拦截到请求
        log.info("拦截到请求:{}", request.getRequestURI());
        //获取请求的URL
        String requestURL = request.getRequestURI();
        String[] urls = new String[]{
          "/employee/login",
          "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources/**",
                "/v2/api-docs"
        };
        for ( String str : urls ) {
            if ( PATH_MATCHER.match ( str , requestURL ) ) {
                log.info ("请求URL:{} 是需要放行的URL", requestURL);
                filterChain.doFilter ( request , response );
                return;
            }
        }
        //获取session
        if(request.getSession ().getAttribute ("employee") != null){
            log.info ("用户已登录，用户id为{}", request.getSession ().getAttribute ("employee"));

            Long id = (Long) request.getSession ().getAttribute ("employee");
            log.info ("设置当前线程用户id为{}", id);
            BaseContext.setCurrentId (id);

            filterChain.doFilter ( request , response );
            return;
        }

        //移动端用户
        if(request.getSession ().getAttribute ("user") != null){
            log.info ("用户已登录，用户id为{}", request.getSession ().getAttribute ("user"));

            Long userId = (Long) request.getSession ().getAttribute ("user");
            log.info ("设置当前线程用户id为{}", userId);
            BaseContext.setCurrentId (userId);

            filterChain.doFilter ( request , response );
            return;
        }
        //跳转到登录页面
        log.warn ("用户未登录，跳转到登录页面");
        response.getWriter ().write (JSON.toJSONString (Result.error ("NOTLOGIN")));
        return;
    }
}
